<?php
namespace app\common\traits\wechat;

use Thenbsp\Wechat\OAuth\Client;
use Thenbsp\Wechat\Bridge\Http;
use think\Log;

trait WechatUserInfo
{
    use WechatAccessToken;

    /**
     * 网页授权获取用户信息
     * @param string $params['backUrl'] 授权回调地址
     * @param string $params['state'] 应用授权作用域
     * @param string $params['scope'] 授权方式
     * @return array
     */
    public function getAuthUserInfo(array $params = [])
    {
        $appid = config('wechat.appid');
        $appsecret = config('wechat.appsecret');

        $client = new Client($appid, $appsecret);
        $client->setScope('snsapi_userinfo');

        if (isset($params['backUrl'])) {
            $backUrl = $params['backUrl'] ? : '';
            $client->setRedirectUri($backUrl);
        }

        if (isset($params['state'])) {
            $state = $params['state'] ? : '';
            $client->setState($state);
        }

        $code = input('code', false);
        if(!$code) {
            header('Location: '.$client->getAuthorizeUrl());
            exit;
        }

        $accessToken = $client->getAccessToken($code);
        $userinfo = $accessToken->getUser();
        return $userinfo;
    }

    /**
     * 获取指定用户信息
     * @param string $openid 用户的openid
     * @return \Doctrine\Common\Collections\ArrayCollection|string
     * @throws \Exception
     */
    public function getUserInfo($openid)
    {
        $accessToken = $this->getAccessToken();
        $userInfoUrl = 'https://api.weixin.qq.com/cgi-bin/user/info';

        $query = [
            'access_token' => $accessToken,
            'openid' => $openid,
            'lang' => 'zh_CN',
        ];

        $response = Http::request('GET', $userInfoUrl)
            ->withQuery($query)
            ->send();

        if( $response['errcode'] != 0 ) {
            throw new \Exception($response['errmsg'], $response['errcode']);
        }

        return $response;
    }
}